<?php

namespace App\Library\Logic;

use App\Library\Lock;
use App\Library\Requests\Product\DayTjRequest;
use App\Library\Requests\Product\ProductPageRequest;
use App\Models\BuyWillModel;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class BuyWillLogic extends BuyWillModel
{
    /**
     * createData
     * @param string $serialNumber
     * @param int $quantity
     * @return string|array
     */
    public static function createData(string $serialNumber, int $quantity): string|array
    {
        $self = self::findBySerialNumber($serialNumber);
        if (is_null($self)) return '顺手买商品不存在';
        else if ($self->status !== 1) return '顺手买商品已下架';
        else if ($self->stock <= $quantity) return '顺手买商品库存不足';
        else if ($self->limit > 0) {
            if ($self->limit < $quantity) return "顺手买数量($quantity)大于限购数量($self->limit)";
            $count = self::limit($self->id);
            if ($quantity + $count > $self->limit) {
                return "顺手买数量($quantity)+已购买数量($count)大于限购数量($self->limit)";
            }
        }
        return [
            'sellerId' => $self->user_id,
            'productFileId' => $self->file_id,
            'title' => $self->title,
            'originalPrice' => $self->price,
            'specialPrice' => $self->price,
            'price' => $self->price,
            'quantity' => $quantity,
            'buyWillId' => $self->id,
            'info' => $self,
        ];
    }

    /**
     * limit
     * @param int $id
     * @return int
     */
    public static function limit(int $id): int
    {
        return ShopOrderGoodsLogic::query()
            ->leftJoin('shop_order', 'shop_order.order_id', 'shop_order_goods.order_id')
            ->where('buy_user_id', USERID)
            ->where('order_buy_status', '<>', 3)
            ->where('buy_will_id', $id)->count();
    }

    /**
     * limit
     * @param int $id
     * @param int $quantity
     * @param string $symbol
     */
    public static function editStock(int $id, int $quantity, string $symbol = '+'): void
    {
        Lock::get(implode('-', ['buyWill', $id]), function () use ($id, $quantity, $symbol) {
            $symbolTwo = $symbol === '+' ? '-' : '+';
            self::updateById([
                'sales' => DB::raw('sales' . $symbol . $quantity),
                'stock' => DB::raw('stock' . $symbolTwo . $quantity),
            ], $id);
        });

    }

    public static function dayTj(DayTjRequest $request): Collection|array
    {
        $builder = self::query();
        if (USERID === MAINID || POWER === 1) $builder->where('user_id', MAINID);
        else $builder->where('add_user_id', USERID);
        return $builder->select(
            DB::raw('count(*) as day_count'),
            DB::raw('left(created_at, 10) as day'),
        )->groupBy('day')->orderByDesc('created_at')->where('status', $request->status)->get();
    }

    public static function paging(ProductPageRequest $request): array
    {
        $builder = self::query()->where('status', $request->buyWillStatus);
        if (USERID === MAINID || POWER === 1) $builder->where('user_id', MAINID);
        else $builder->where('add_user_id', USERID);
        if (!is_null($request->startAt)) {
            $builder->whereBetween('created_at', [
                now()->parse($request->startAt)->startOfDay()->format('Y-m-d H:i:s'),
                now()->parse($request->endAt)->endOfDay()->format('Y-m-d H:i:s')
            ]);
        }
        if (!is_null($request->keyword)) {
            $builder->where(function ($query) use ($request) {
                $query->where('title', 'LIKE', '%' . $request->keyword . '%')
                    ->orWhere('description', 'LIKE', '%' . $request->keyword . '%');
            });
        }
        return paginate($builder->orderBy('created_at', $request->orderBy)->paginate($request->limit));
    }

    public function rand(string $shopUserId): array
    {
        return DB::select('
            SELECT * FROM `buy_will` WHERE `buy_will`.`deleted_at` IS NULL AND `buy_will`.`status` = 1 AND `buy_will`.`stock` > 0 AND (
            `buy_will`.`limit` = 0 OR `buy_will`.`limit` > (
                SELECT COUNT(*) FROM `shop_order_goods` LEFT JOIN `shop_order` ON `shop_order`.`order_id` = `shop_order_goods`.`order_id`
                WHERE `shop_order`.`buy_user_id` = ' . USERID . ' AND `shop_order_goods`.`buy_will_id` = `buy_will`.`id`
            )) and `buy_will`.`user_id` in (' . $shopUserId . ') order by RAND() limit 3
        ');
    }
}
